package com.study.exception;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.study.entity.common.CommonResponseEntity;
import com.study.enumeration.ResponseEnum;
import com.study.util.ResponseUtil;

//@ControllerAdvice+@ResponseBody，开启全局的异常捕获，返回JSON
@RestControllerAdvice
public class GlobalExceptionHandler {

	/**
	 * 处理自定义异常
	 * 
	 * @param e 自定义异常
	 * @return
	 * @ExceptionHandler 说明捕获哪些异常，对那些异常进行处理
	 */
	@ExceptionHandler(value = DefinitionException.class)
	public CommonResponseEntity<Object> customExceptionHandler(DefinitionException e) {
		return ResponseUtil.defineError(e);
	}

	/**
	 * 处理其他异常
	 * 
	 * @param e 异常
	 * @return
	 */
	@ExceptionHandler(value = Exception.class)
	public CommonResponseEntity<Object> exceptionHandler(Exception e) {
		if (e instanceof NullPointerException) {
			// 捕获空指针异常
			return ResponseUtil.otherError(ResponseEnum.NOT_PARAM);
		} else if (e instanceof IllegalAccessException) {
			// 非法访问异常
			return ResponseUtil.otherError(ResponseEnum.NO_PERMISSION);
		} else {
			return ResponseUtil.otherError(ResponseEnum.SERVER_ERROR);
		}
	}
}
